package org.example.curriculum_design_6_16.mapper;

import org.apache.ibatis.annotations.*;
import org.example.curriculum_design_6_16.entity.pojo.UserRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.example.curriculum_design_6_16.entity.pojo.UserRoleKey;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
* @author 郑凯
* @description 针对表【user_role】的数据库操作Mapper
* @createDate 2025-06-16 13:21:18
* @Entity org.example.curriculum_design_6_16.entity.pojo.UserRole
*/
@Mapper
@Repository
public interface UserRoleMapper extends BaseMapper<UserRole> {
    UserRole selectByCompositeKey(UserRoleKey key);
    int deleteByCompositeKey(UserRoleKey key);
    int updateByCompositeKey(UserRole record);
    /**
     * 为用户分配角色
     * @param userId 用户ID (VARCHAR)
     * @param roleId 角色ID (VARCHAR)
     * @return 影响的行数
     */
    @Insert("INSERT INTO user_role(user_id, role_id, assigned_at) " +
            "VALUES(#{userId}, #{roleId}, NOW())")
    int assignRole(@Param("userId") String userId, @Param("roleId") String roleId);

    /**
     * 检查用户是否已有某角色
     * @param userId 用户ID
     * @param roleId 角色ID
     * @return 是否已分配
     */
    @Select("SELECT COUNT(*) FROM user_role " +
            "WHERE user_id = #{userId} AND role_id = #{roleId}")
    boolean existsUserRole(@Param("userId") String userId, @Param("roleId") String roleId);

    /**
     * 删除用户的某个角色
     * @param userId 用户ID
     * @param roleId 角色ID
     * @return 影响的行数
     */
    @Delete("DELETE FROM user_role " +
            "WHERE user_id = #{userId} AND role_id = #{roleId}")
    int removeRole(@Param("userId") String userId, @Param("roleId") String roleId);

    /**
     * 删除用户的所有角色
     * @param userId 用户ID
     * @return 影响的行数
     */
    @Delete("DELETE FROM user_role WHERE user_id = #{userId}")
    int clearUserRoles(@Param("userId") String userId);

    /**
     * 更新角色分配人
     * @param userId 用户ID
     * @param roleId 角色ID
     * @param assignedBy 分配人ID
     * @return 影响的行数
     */
    @Update("UPDATE user_role SET assigned_by = #{assignedBy} " +
            "WHERE user_id = #{userId} AND role_id = #{roleId}")
    int updateAssigner(@Param("userId") String userId,
                       @Param("roleId") String roleId,
                       @Param("assignedBy") String assignedBy);

    @Select("SELECT r.role_name FROM user_role ur " +
            "JOIN role r ON ur.role_id = r.role_id " +
            "WHERE ur.user_id = #{userId}")
    String findRoleNamesByUserId(@Param("userId") String userId);
}




